package com.cqc.lite.utils;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * commons-io实现csv的读取与生成
 <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.7</version>
 </dependency>
 **/
public class CommonIOUtil {

    //字符集： UTF-8  GBK
    public static String charsetName = "UTF-8";
    //分隔符
    public static String delimiterString = ",";
    public static char delimiterChar = ',';

    public static void downloadCsv(HttpServletRequest request, HttpServletResponse response,
                                   List<String> lines, String fileName) {
        //设置下载的响应头信息
        response.setCharacterEncoding(charsetName);
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        String mimeType = request.getSession().getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);

        ServletOutputStream os = null;
        try {
            //String lineEnding  = new StringBuilderWriter(4).toString();
            os = response.getOutputStream();
            IOUtils.writeLines(lines,null,os,StandardCharsets.UTF_8);//写入多行数据局
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(os,null);
        }
    }


    public static List<String[]>  readCsv(MultipartFile multipartFile) {
        List<String[]> dataList = new ArrayList<>();
        InputStream is = null;
        try {
            is = multipartFile.getInputStream();
            List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8);
            for (String line : lines) {
                if(StringUtils.hasLength(line)){
                    String[] arr = line.split(",");
                    dataList.add(arr);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(is,null);
        }
        return dataList;
    }

}
